'''
Entry of WEBlog

Created on 2012-10-26

@author: DANG Zhengfa
'''
# load system modules
import webapp2
# from webapp2 import RequestHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from webapp2 import Route, uri_for
from webapp2_extras.routes import RedirectRoute
from webapp2_extras import json
from model import DBPhoto, Setting
import logging

# load modules defined by this app
from utilities import render_template, get_safe_slug
from BaseRequestHandler import BaseRequestHandler


class Admin(BaseRequestHandler):
    '''
    classdocs
    '''

    def get(self):
        # find stats for this blog
        stats = {}
        stats['public'] = DBPhoto.all().filter("public =", True).count()
        stats['private'] = DBPhoto.all().filter("public =", False).count()

        t_values = {}
        t_values['stats'] = stats
        return self.response.out.write(render_template("index.html", t_values, "", True))


class SettingHandler(BaseRequestHandler):
    """manage external links for this blog"""
    def get(self):
        t_values = {}
        logging.info("SettingHandler")

        # find the only record in setting db
        settings = Setting.all()
        if settings.count() == 0:
            logging.error("Wrong records in Setting")
            setting = Setting()
            setting.put()
        else:
            setting = settings[0]

        t_values["setting"] = setting
        return self.response.out.write(render_template("settings.html", t_values, "", True))

    def post(self):
        setting_id = self.request.POST.get('setting_id')
        host = self.request.POST.get('host')
        headline = self.request.POST.get('headline')
        text = self.request.POST.get('text')
        start_date = self.request.POST.get('start_date')
        logging.info("SettingHandler post: setting_id = %s, headline = %s, text = %s, start_date = %s" % (setting_id, headline, text, start_date))

        result = {'message': '', 'status': 'success', 'content': ''}

        if setting_id:
            # edit existed setting
            setting = Setting.get_by_id(long(setting_id))
            setting.host = host
            setting.headline = headline
            setting.text = text
            setting.start_date = start_date
            setting.put()
            result['message'] = "setting has been saved"
            logging.info(result['message'])
        else:
            result['message'] = "No Setting yet"
            logging.info(result['message'])

        self.response.content_type = 'application/json'
        return self.response.out.write(json.encode(result))


class PhotoManager(BaseRequestHandler):
    """manage categoriesfor this blog"""

    # generate link pairs for navlist
    # format: (link_url, link_label)
    def _generateNavList(self, total_posts, current_page, posts_per_page, base_url):
        navlist = []
        if total_posts > posts_per_page:
            # we need more than one pages
            total_pages = total_posts / posts_per_page
            if (total_posts % posts_per_page) != 0:
                total_pages += 1

            # generate links
            for page_number in range(1, total_pages + 1):
                if page_number != current_page:
                    navlist.append(("%s/%d" % (base_url, page_number), "%d" % (page_number)))

            if current_page > 1:
                navlist.insert(0, ("%s/%d" % (base_url, current_page - 1), "Prev"))
            if current_page < total_pages:
                navlist.append(("%s/%d" % (base_url, current_page + 1), "Next"))
        return navlist

    def get(self, page="1"):
        t_values = {}
        page = int(page)
        logging.info("PhotoManager - get: page = %d" % (page))

        # find all photos
        query = DBPhoto.all().order("-start_date")

        # pagination
        total_photos = query.count()
        max_items_in_page = 10  # hardcoded, should be configured in settings
        q_offset = (page - 1) * max_items_in_page

        logging.info("total photos = %d, current_page = %d, posts_per_page = %d" % (total_photos, page, max_items_in_page))
        t_values['navlist'] = self._generateNavList(total_photos, page, max_items_in_page, uri_for("admin.photos"))
        # logging.info(t_values['navlist'])

        # get resutls
        photos = query.fetch(limit=max_items_in_page, offset=q_offset)
        t_values["photos"] = photos
        t_values["post_url"] = "%s/%d" % (uri_for("admin.photos"), page)

        # logging.info(t_values["post_url"])

        return self.response.out.write(render_template("photos.html", t_values, "", True))

    def get_file_size(self, file):
        file.seek(0, 2)  # Seek to the end of the file
        size = file.tell()  # Get the position of EOF
        file.seek(0)  # Reset the file position to the beginning
        return size

    # add new link, or update existed link
    def post(self, page=""):
        result = {'message': '', 'status': 'success', 'content': ''}

        # get operation and current_photo_id
        operation = self.request.POST.get("operation")
        current_photo_id = self.request.POST.get("current_photo_id")
        if operation == "delete":
            photo = DBPhoto.get_by_id(long(current_photo_id))
            if photo:
                result['message'] = "photo %s (id=%s) has been removed!" % (photo.photo_name, current_photo_id)
                logging.info(result['message'])
                photo.remove()  # user defined remove methods
            else:
                result['message'] = "photo id = %s does not exist" % (current_photo_id)
                logging.info(result['message'])

            self.response.content_type = 'application/json'
            return self.response.out.write(json.encode(result))

        # get information from request
        logging.info(self.request.POST)
        photofile = self.request.POST.get("photofile")
        headline = self.request.POST.get("headline")
        text = self.request.POST.get("text")
        public = self.request.POST.get("public")
        start_date = self.request.POST.get("startdate")
        end_date = self.request.POST.get("enddate")
        public = self.request.POST.get("public")

        # logging.info("PhotoManager post: photofile = %s, headline = %s, text = %s, public = %s, start_date = %s, end_date = %s, public = %s" % (photofile.filename, headline, text, public, start_date, end_date, public))

        if current_photo_id:
            photo = DBPhoto.get_by_id(long(current_photo_id))
        else:
            photo = DBPhoto.create(photofile.filename, photofile.file.read())
        photo.headline = headline
        photo.text = text
        photo.start_date = start_date
        photo.end_date = end_date
        if public == "on":
            photo.public = True
        else:
            photo.public = False
        photo.put()

        if page:
            self.redirect("%s/%s" % (uri_for("admin.photos"), page))
        else:
            self.redirect(uri_for("admin.photos"))

# define routers
# see http://webapp-improved.appspot.com/api/webapp2_extras/routes.html
routes = [
          RedirectRoute('/admin/', handler='admin.Admin', name="admin", strict_slash=True),
          Route('/admin/photos', handler='admin.PhotoManager', name="admin.photos"),
          Route('/admin/photos/<page>', handler='admin.PhotoManager', name="admin.photos.operation"),
          Route('/admin/settings', handler='admin.SettingHandler', name="admin.settings"),
          ]

application = webapp2.WSGIApplication(routes, debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
